﻿using Basic.FlowApplication.AuditLocalEvent;
using Basic.FlowApplication.Interface;
using Basic.FlowApplication.Model;
using Basic.FlowApplication.Model.AuditLog;
using Basic.FlowModel.AuditLog;
using Basic.FlowRemoteModel;
using WeDonekRpc.Helper;

namespace Basic.FlowApplication.Extend
{
    internal class AuditCloseService : IAuditCloseService
    {
        private readonly IAuditLogService _AuditLog;
        private readonly IFlowNodeService _Flow;

        public AuditCloseService ( IAuditLogService auditLog, IFlowNodeService flow )
        {
            this._AuditLog = auditLog;
            this._Flow = flow;
        }

        public void Close ( long logId, long empId )
        {
            FlowAuditLogState log = this._AuditLog.GetLogState(logId);
            if ( log.Status == FlowAuditLogStatus.已结束 )
            {
                throw new ErrorException("flow.audit.already.end");
            }
            AuditFlowBody flow = this._Flow.Get(log.FlowId);
            FlowAuditLogStatus oldStatus = log.Status;
            FlowAuditStatus oldAuditStatus = log.AuditStatus;
            log.AuditStatus = FlowAuditStatus.已关闭;
            log.EndEmpId = empId;
            log.ToVoidRunItem(flow, flow.BeginNode, null);
            log.SyncNodeState();
            SaveAuditBody body = log.GetAuditBody(flow);
            AuditLog res = this._AuditLog.SaveResult(body);
            new FlowAuditEvent
            {
                OldLogStatus = oldStatus,
                OldAuditStatus = oldAuditStatus,
                Flow = flow,
                ItemId = flow.BeginNode,
                NodeState = body.NodeState,
                Item = log.LogItem.Find(c => c.Id == log.BeginItemId),
                Log = res
            }.AsyncSend();
        }

    }
}
